<?php

namespace App\Models;

use App\Enums\AssetSourceType;
use App\Enums\OrderStatus;
use App\Enums\ProductType;
use App\Enums\TransStatus;
use BenSampo\Enum\Traits\CastsEnums;

/**
 * @mixin IdeHelperOrder
 */
class Order extends BaseModel
{
    use CastsEnums;

    protected $casts = [
        'order_status' => OrderStatus::class,
        'trans_status' => TransStatus::class,
    ];

    protected $appends = [
        'display_sale_price',
        'display_order_amount',
    ];

    public function payment()
    {
        return $this->hasOne(OrderPayment::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function user()
    {
        return $this->belongsTo(FrontendUser::class, 'user_id');
    }

    public function assets()
    {
        return $this->hasMany(Asset::class, 'source_id')->where('source_type', AssetSourceType::ORDER);
    }

    public static function generateOrderNo(ProductType $type)
    {
        $prefix = 'S';
        if ($type->is(ProductType::RESALE())) {
            $prefix = 'R';
        }
        if ($type->is(ProductType::BLIND_BOX())) {
            $prefix = 'B';
        }

        return $prefix . now()->format('YmdHis') . rand(1000, 9999);
    }

    public function getDisplaySalePriceAttribute()
    {
        return toYuan($this->sale_price);
    }

    public function getDisplayOrderAmountAttribute()
    {
        return toYuan($this->order_amount);
    }
}
